import {Table, Menu, Dropdown, Icon, message} from 'antd';
// import Table from '../../../_antd1.11.2/table'
// import Menu from '../../../_antd1.11.2/menu'
// import Dropdown from '../../../_antd1.11.2/dropdown'
// import Icon from '../../../_antd1.11.2/icon'
// import message from '../../../_antd1.11.2/message'

import cloneDeep from 'lodash/cloneDeep'

const MenuItem = Menu.Item;

import * as API from './api/index'
//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	customColTitle: '定制列',
  	customColSelect: '待选列名',
  	customColSelected: '已选列名',
  	customColSave: '保存',
  	customColCancel: '取消',
};

class WeaNewTable extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
	constructor(props) {
		super(props);
		this.state = {
			height: props.scrollHeight || 0,
			showCheck: props.showCheck || false,
			columns: [],
			datas: [],
			operates: [],
			sortParams: [],
			//pagination
			selectedRowKeys: [],
			current: 1,
			count: 0,
			pageSize: 10,
			loading: false,

		}
	}
	setScrollheigth() {
		const { heightSpace } = this.props;
		let hs = heightSpace || 0;
		if(jQuery(".wea-new-table") && jQuery(".wea-new-table .ant-pagination.ant-table-pagination")) {
			let widowClientHeight = document.documentElement.clientHeight || 0;
			let top = jQuery(".wea-new-table").offset() ? jQuery(".wea-new-table").offset().top : 0;
			let bottom = jQuery(".wea-new-table .ant-pagination.ant-table-pagination").height() || 30;
			let scrollheigth = widowClientHeight - top - bottom;
			this.setState({
				height: scrollheigth - 100 - hs
			})
		}
	}
	componentWillReceiveProps(nextProps, nextState) {
		if((!this.props.dataKey && nextProps.dataKey) ||
			(this.props.dataKey && nextProps.dataKey && this.props.dataKey !== nextProps.dataKey)
		) {
			this.getTableDatas(nextProps.dataKey)
		} else if(this.props.refreshDatas !== nextProps.refreshDatas) {
			this.getTableDatas()
		}
	}
	//	shouldComponentUpdate(nextProps,nextState) {
	//		return this.state.height !== nextState.height ||
	//			this.state.current !== nextState.current ||
	//			this.state.count !== nextState.count ||
	//			this.state.pageSize !== nextState.pageSize ||
	//			this.state.showCheck !== nextState.showCheck ||
	//			this.props.refreshDatas !== nextProps.refreshDatas ||
	//			this.props.dataKey !== nextProps.dataKey ||
	//			JSON.stringify(this.state.columns) !== JSON.stringify(nextState.columns) ||
	//			JSON.stringify(this.state.datas) !== JSON.stringify(nextState.datas) ||
	//			JSON.stringify(this.state.operates) !== JSON.stringify(nextState.operates) ||
	//			JSON.stringify(this.state.selectedRowKeys) !== JSON.stringify(nextState.selectedRowKeys) ||
	//			JSON.stringify(this.state.sortParams) !== JSON.stringify(nextState.sortParams);
	//	}
	componentDidMount() {
		this.setScrollheigth();
		jQuery(window).resize(() => {
			this._reactInternalInstance !== undefined && this.setScrollheigth();
		});
	}
	render() {
		//scroll : 启用内部滚动 false(默认)
		//heightSpace : 启用内部滚动后高度调整 Number
		//usePagination : 是否开启 table分页  true(默认)
		//size : 正常或迷你类型，default(默认)、 small
		//useFixedHeader : 是否固定表头 false(默认)
		//bordered : 是否展示外边框和列边框 false(默认)
		//showHeader : 是否显示表头 true(默认)
		//useFilters : 使用过滤 false(默认)
		//useSorter : 使用排序 true(默认)
		//showCheck : 是否展示复选 默认 false(默认)
		//checkType : checkbox(默认) OR radio
		//noOperate : 不增加操作行 false(默认)
		//refreshDatas : 是否触发table 接口 false(默认) 第一次触发之前,需要先传入一次datakey,每次触发接口需 false->true
		//useLoading : 是否开启table 自身loading false(默认)
		//---------pagination----------
		//showSizeChanger : 显示分页大小选择 true(默认)
		//showQuickJumper : 显示快速跳转 true(默认)
		//showTotal : 显示总数量 true(默认)
		//---------function----------
		//onChange(pagination,filter,sorter) : 获取table操作 分页、排序、本地过滤、信息 (obj,obj,obj)
		//getSelection(selectedRowKeys) : 获取选中行信息 (string)
		//getTableLoading(bool) : 获取table 加载状态 (bool)
		//onRowClick(record,index) : 行点击事件 (obj,number)
		const locale = this.getLocale();
		const { scroll, heightSpace, usePagination, size, useFixedHeader, bordered, showHeader, useFilters, useSorter, noOperate, checkType, useLoading } = this.props;
		const { height, columns, datas, operates, selectedRowKeys, showCheck, loading, sortParams } = this.state;
		const scrollHeight = scroll ? { scroll: { y: height } } : {};
		const newLoading = useLoading ? { loading: loading } : {};
		let newColumns = this.getColumns(columns);
		let oldWidthObj = {}
		let num = 0;
		let nowWidth = 0;
		newColumns = newColumns.filter(newColumn => {
			if(newColumn.display === "true") {
				const width = newColumn.oldWidth ? parseFloat(newColumn.oldWidth.substring(0, newColumn.oldWidth.length - 1)) : 10;
				oldWidthObj[newColumn.dataIndex] = width;
				num++;
				nowWidth += width;
			}
			return newColumn.display === "true";
		});
		!noOperate && newColumns.push({
			title: "操作",
			dataIndex: "randomFieldOperate",
			key: "randomFieldOperate",
			width: "10%",
			render(text, record, index) {
				const rfs = record.randomFieldOp ? JSON.parse(record.randomFieldOp) : {};
				let argumentString = [];
				!!record.randomFieldOpPara && record.randomFieldOpPara.map(r => { argumentString.push(r.obj) })

				let showOperate = null;
				let shouFn = null;
				let hiddenOperate = new Array();
				let opNum = 0;
				operates.map((operate, index) => {
					let flag = operate.index || "-1";
					if(rfs[flag] && rfs[flag] != "false") opNum++;
					let fn = !!operate.href ? `${operate.href.split(':')[1].split(')')[0]}${record.randomFieldId},${argumentString});` : ""
					if(rfs[flag] && rfs[flag] != "false") {
						hiddenOperate.push(
							<MenuItem>
                                <a href='javascript:void(0);' onClick={()=>{eval(fn)}}>{operate.text}</a>
                            </MenuItem>
						);
					}
				});
				const menu = (
					<Menu>
                        {hiddenOperate}
                    </Menu>
				)
				return(
					<div>
                        {hiddenOperate.length>0 &&
                        (<Dropdown overlay={menu}>
                            <a className="ant-dropdown-link" href="javascript:void(0);">
                                <Icon type="down" />
                            </a>
                        </Dropdown>)}
                    </div>
				)
			}
		});
		nowWidth += 8; //操作按钮
		if(showCheck) nowWidth += 2; //check框位置
		newColumns = newColumns.map((newColumn) => {
			if(newColumn.display === "true") {
				newColumn.width = (
					parseFloat(oldWidthObj[newColumn.dataIndex]) +
					(100 - nowWidth) * parseFloat(oldWidthObj[newColumn.dataIndex] / nowWidth)
				) + "%";
				if(useSorter !== false && newColumn.orderkey) {
					newColumn.sorter = true;
					if(sortParams && sortParams.length > 0) {
						sortParams.map(s => {
							if(s.orderkey == newColumn.orderkey)
								newColumn.sortOrder = s.sortOrder;
						});
					} else {
						newColumn.sortOrder = false;
					}
				}
				return newColumn;
			}
			return newColumn;
		});
		const rowSelection = showCheck ? {
			selectedRowKeys: selectedRowKeys,
			onChange: (sRowKeys, sRows) => {
				this.setState({ selectedRowKeys: sRowKeys });
				if(typeof this.props.getSelection == 'function') {
					this.props.getSelection(`${sRowKeys}`, sRows);
				}
			},
			getCheckboxProps: record => {
				return { disabled: record["randomFieldCk"] !== "true" };
			}
		} : null;
		return(
			<div className="wea-new-table">
                <Table {...scrollHeight}
                	rowSelection={rowSelection}
                	columns={newColumns}
                	dataSource={datas}
                	pagination={this.getPagination()}
                	checkType={checkType || 'checkbox'}
                	rowKey={record => record.randomFieldId}
                	onRowClick={this.onRowClick.bind(this)}
                	onChange={this.onChange.bind(this)}
                	/>
            </div>
		)
	}
	getPagination() {
		//showSizeChanger 默认开启 true
		//showQuickJumper 默认开启 true
		//showTotal 默认开启 true
		const locale = this.getLocale();
		const { showSizeChanger, pageSizeOptions, showQuickJumper, pageinationSize, showTotal } = this.props;
		const { current, count } = this.state;
		let obj = {
			defaultCurrent: 1,
			defaultPageSize: 10,
			current: current,
			count: count,
			size: pageinationSize ? pageinationSize : '',
			total: count,
			showSizeChanger: showSizeChanger === false ? false : true,
			showQuickJumper: showQuickJumper === false ? false : true,
			pageSizeOptions: pageSizeOptions ? pageSizeOptions : [10, 20, 50, 100],
		};
		if(showTotal !== false) {
			obj.showTotal = total => { return `${locale.total} ${total} ${locale.totalUnit}`; }
		}
		return obj
	}
	getTableDatas(key, clear=true, c, p, s) {
		const { dataKey } = this.props;
		const { current, pageSize, sortParams } = this.state;
		let newCurrent = c ? c : current;
		if(clear) newCurrent = 1;//页码回到1
		let newPageSize = p ? p : pageSize;
		let newSortParams = s ? s : sortParams;
		let newDataKey = key ? key : dataKey;

		let min = newPageSize * (newCurrent - 1) + 1;
		let max = newPageSize * newCurrent;
		//如需清除状态
		let newClear = clear == false ? clear : true;
		if(newClear) {
			min = 1;
			max = newPageSize;
			newSortParams = [];
			this.setState({ current: 1, pageSize: 10, sortParams: [], selectedRowKeys: '' });
		}
		if(typeof this.props.getTableLoading == 'function') this.props.getTableLoading(true);
		if(newDataKey) {
			Promise.all([
				API.getTableDatas({ dataKey: newDataKey, min: min, max: max, sortParams: JSON.stringify(newSortParams) }).then(data => {
					this.setState({
						current: newCurrent,
						datas: data.datas,
						columns: data.columns,
						operates: data.ops,
						showCheck: data.haveCheck,
						sortParams: newSortParams
					});
					return data;
				}),
				//	            API.getTableSet({dataKey:newDataKey}).then(data => {
				//	                this.setState({
				//	            		count: data.count,
				//	            		columns: data.columns,
				//	            		operates: data.ops,
				//	            		showCheck: data.haveCheck,
				//	            		sortParams: newSortParams
				//	            	});
				//	                return data;
				//	            })
				API.getTableCounts({ dataKey: newDataKey }).then(data => {
					this.setState({
						count: data.count,
					});
					if(typeof this.props.onChange == 'function'){
						this.props.onChange({count: data.count, current: newCurrent, pageSize: newPageSize});
					}
					return data;
				})
			]).then(result => {
				const doCheckApi = result[0].haveCheck;
				const ops = result[0].ops;
				if(doCheckApi || (ops && ops.length>0)){
					const columns = result[0].columns;
					const checkDatas = result[0].datas;
					let newDatas = [];
					checkDatas.map(d => {
						let newData = {};
						columns.map(c => {
							if((c.from && c.from === 'set') || c.dataIndex === 'randomFieldId')
								newData[c.dataIndex] = d[c.dataIndex];
						})
						newDatas.push(newData);
					})
					API.getTableChecks({ randomDatas: JSON.stringify(newDatas), dataKey: dataKey }).then(data => {
						let datas = this.state.datas;
						let nDatas = data.datas;
						datas = datas.map(d => {
							let newN = cloneDeep(d);
							nDatas.map(n => {
								if(n.randomFieldId == d.randomFieldId) {
									for(let p in n) {
										newN[p] = n[p];
									}
								}
							})
							return newN
						})
						this.setState({ datas: datas });
						if(typeof this.props.getTableLoading == 'function') this.props.getTableLoading(false);
					});
				}
			});
		} else {
			message.error('sessionKet is requred');
		}
	}
	onChange(pagination, filters, sorter) {
		let params = {
			current: pagination.current,
			pageSize: pagination.pageSize,
			sortParams: sorter.column ? [{ orderkey: sorter.column.orderkey, sortOrder: sorter.order }] : []
		}
		this.setState(params)
		this.getTableDatas('', false, params.current, params.pageSize, params.sortParams);
	}
	onRowClick(record, index) {
		if(typeof this.props.onRowClick == 'function')
			this.props.onRowClick(record, index);
	}
	getColumns(columns) {
		let newColumns = cloneDeep(columns);
		return newColumns.map((column) => {
			let newColumn = column;
			newColumn.render = (text, record, index) => { //前端元素转义
				let valueSpan = record[newColumn.dataIndex + "span"];

				function createMarkup() { return { __html: valueSpan }; };
				return(
					<div className="wea-url" dangerouslySetInnerHTML={createMarkup()} />
				)
			}
			return newColumn;
		});
	}
}


export default WeaNewTable;